// Copyright 2007 Helsinki Institute for Information Technology
// and the authors.
//
// Authors: Harri Hämäläinen <harri.hamalainen@helsinki.fi>
//          Toni Ruottu <toni.ruottu@iki.fi>

// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation files
// (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

var collection = location.pathname.split('/')[2];
var MAX_TAGS_ATTIME = 3;

onload = function () {
    var q = Util.get_params();
    if (q.page == 'torrent_info') {
        var torrentpath = q.torrent.split('/');
        new TorrentView(torrentpath[0], torrentpath[1]);
    } else if (q.page == 'search' && q.query) {
        new SearchView(q.query);
    } else {
        new MainView();
    }
};

function islandFooter() {

    html = '<ul class="mainmenu">';

    try {
        json = HttpConnector.doGet('/collection/'+collection+'/island/conf');
        conf = json.evalJSON(true);
        coast = conf['coast']
    } catch (e) {
        coast = '';
    }

    html += '<li><a href="javascript:create_new_island(\''+coast+'\')">Found a new island</a></li>'

    if(coast != '') {

        html += '<li><a href=\"/collection/'+ coast +'/web/index.html\">Visit coast nearby</a></li>';

        html += '<li><a href="/coast/'+coast+'/teachpilot?island='+ collection +'">Teach a pilot</a></li>';
    }

    html += '</ul>';

    return html;
}


function MainView () {

    var connector = new TrackerConnector();
    var torrents = connector.getTorrentfiles(collection);
    var infos = connector.getTorrentinfos(collection);

    var html = '<div class="thisplace"><h1><a href="/collection/' + collection +
        '/web/index.html"><img src="/static/icons/fusion_island.png" alt="" />' +
        HttpConnector.doGet('/collection/'+collection+'/info/title') +
        '<img src="/static/icons/fusion_island.png" alt="" /></a></h1>';


    
    html += '<div class="publishpanel">'
        + '<table><tr>'
        + '<td class="help">'
        + '<div class="help"><ol>'
        + '<li>choose a torrent-file<br /><span class="sidenote">Announce url is automagically changed to point at a distributed tracker that comes with your island.</span></li>'
        + '<li>write a description</li>'
        + '<li>press Upload button</li>'
        + '<li>download torrent-file<br /><span class="sidenote">The announce url was changed during the upload.</span></li>'
        + '<li>seed</li>'
        + '</ol>'
        + ''
        + '</div>'
        + '</td>'
        + '<td class="panel">'
        + '<form>'
        + '<strong>Publish</strong> '
        + '<input id="publish_file" type="file" value="" /><br />'
        + '<label class="inputlabel" for="publish_description">Description:</label>'
        + '<textarea id="publish_description" class="description" rows="10" cols="40" ></textarea><br />'
        + '<div class="buttonpanel"><input id="publish_button" type="button" value="Upload" /></div>'
        
        +'</form>'
        + '</td>'
        + '</tr></table>'
        + '</div>'

    html += '<table><tr><th>Tags</th><th>Name</th><th>Published</th><th class="get"></th><th>Size</th><th title="Seeders">S</th><th title="Leechers">L</th></tr>';

    for (var i = 0; i<torrents.length; i++) {
        var infohash = torrents[i][0].slice(0, 40); //(\w*)\/file\/.*$/)[1];
        var torrent = torrents[i][0].match(/\w*\/file\/(.*)$/)[1];
        var friendlyname = name;

        var torrentinfo = HttpConnector.doGet("/collection/"+collection+"/island/"+infohash+"/info/"+torrent+"/info").evalJSON(true);

//         for (var j=0; j<infos.length; j++) {
//             if (infos[j][0] == infohash+"/info/"+torrent+"/info") {
//                 torrentinfo = infos[j][1].evalJSON(true);
//             }
//         }

        var status = HttpConnector.doGet("/island/"+collection+"/status?info_hash="+infohash).evalJSON(true);

        html += "<tr><td class=\"tags\">"+TrackerUtils.getNiceTags(connector.getTags(infohash, torrent, collection), MAX_TAGS_ATTIME, null )+"</td>"+
                "<td class=\"filename\"><a href=\"?page=torrent_info&torrent="+infohash+"/"+torrent+"\">"+
                TrackerUtils.friendlyName(torrent)+"</a></td>"+
                "<td>"+Util.getUTCFriendlyDate(torrentinfo["published"]).split(' ')[0]+"</td>"+
                "<td class=\"get\"><a href=\"/collection/"+collection+"/island/"+torrents[i][0]+"\"><img src=\"/static/icons/torrent_download.png\" alt=\"get torrent\" /></a></td>"+
                "<td>"+TrackerUtils.bytesToMbytes(parseInt(torrentinfo["size"]))+"</td>"+
                "<td>"+status["files"][infohash]["complete"]+"</td>"+
                "<td>"+status["files"][infohash]["incomplete"]+"</td></tr>";
    }
    html += '</table>';

    html += '<p class="feedlink"><a href="/island/' + collection + '/feed"><img src="/static/icons/feed-icon-14x14.png" alt=""/> get publications as feed</a></p>';
    html += '</div>';
    
    html += islandFooter();

    $('view').innerHTML +=  html;

    $('publish_button').onclick = function() {
        location = '/island/' + collection + '/publish?'
            + 'description=' + encodeURIComponent($('publish_description').value)
            + '&path=' + encodeURIComponent($('publish_file').value)
            + '&next=/collection/' + collection + '/web/index.html';

    /*
        var nick = $('comment_nickname').value;
        var msg = $('comment_content').value;
        var tags = $('comment_tags').value;
        if (nick==''){
            alert("Nickname cannot be empty");
            return;
        }
        $('comment_content').value = '';
        connector.postComment(infohash, torrent, nick,tags,msg);
    //         $('entry_tags').innerHTML = generic_view.updateTags(entry_path);
    //         $('entry_comments').innerHTML = generic_view.getComments(entry_path);
    */
    };
}

function SearchView(tag) {
    var self = this;
    
    var connector = new TrackerConnector();
    var result = TrackerUtils.searchTag(collection, tag);
    
    var html = '<div class="thisplace"><h1><a href="/collection/' + collection +
    '/web/index.html"><img src="/static/icons/fusion_island.png" alt="" />' +
    HttpConnector.doGet('/collection/'+collection+'/info/title') +
    '<img src="/static/icons/fusion_island.png" alt="" /></a></h1>';

    html += '<h2 class="tagtitle"><span>' + tag + '</span></h2>'

    html += '<table><tr><th>Tags</th><th>Name</th><th>Published</th>'+
        '<th class="get"></th><th>Size</th><th title="Seeders">S</th><th title="Leechers">L</th></tr>';

    for (var i=0; i<result.length; i++) {
        var infohash = result[i][0].split('/')[1];
        var torrent = result[i][0].split('/')[3];
        var torrentinfo = HttpConnector.doGet("/collection/"+collection+"/island/"+infohash+"/info/"+torrent+"/info").evalJSON(true);
        
        var status = HttpConnector.doGet("/island/"+collection+"/status?info_hash="+infohash).evalJSON(true);

        html += "<tr><td class=\"tags\">"+TrackerUtils.getNiceTags(connector.getTags(infohash, torrent, collection), MAX_TAGS_ATTIME, tag )+"</td>"+
                "<td class=\"filename\"><a href=\"?page=torrent_info&torrent="+infohash+"/"+torrent+"\">"+
                TrackerUtils.friendlyName(torrent)+"</a></td>"+
                "<td>"+Util.getUTCFriendlyDate(torrentinfo["published"]).split(' ')[0]+"</td>"+
                "<td class=\"get\"><a href=\"/collection/"+collection+"/island/"+result[i][0]+"\"><img src=\"/static/icons/torrent_download.png\" alt=\"get torrent\" /></a></td>"+
                "<td>"+TrackerUtils.bytesToMbytes(parseInt(torrentinfo["size"]))+"</td>"+
                "<td>"+status["files"][infohash]["complete"]+"</td>"+
                "<td>"+status["files"][infohash]["incomplete"]+"</td></tr>";
    }
    html += '</table>';

    html += '<p class="feedlink"><a href="/island/' + collection + '/feed"><img src="/static/icons/feed-icon-14x14.png" alt=""/> get publications as a feed</a></p>';
    html += '</div>';
    
    html += islandFooter();

    $('view').innerHTML += html;
}

function TorrentView(infohash, torrent) {
    var self = this;
    var connector = new TrackerConnector();
    var MAX_TAGS_ATTIME = 5;
    this.getComments = function() {
        var comments = connector.getComments(collection, infohash, torrent)
        var inner = '';
        
        var comment_template = new Template(
            '<div class="comment"><div class="header"><span><em><a href="/profile/#{profile}">#{author}</a></em>, #{published}</span></div>'
            +'<blockquote>#{content}</blockquote></div>');

        for (var i = 0; i<comments.length; i += 1) {
            var comment = null;
            try {
                comment = comments[i][1].evalJSON(true);
            } catch(e) { continue; }
            var comment_values = {
                published: TrackerUtils.getFancyPublishDate(comment),
                profile: TrackerUtils.getAuthorProfile(comment),
                author: TrackerUtils.getAuthor(comment),
                content: TrackerUtils.getContent(comment)
            }
            inner += comment_template.evaluate(comment_values);
        }
        return inner;
    }
    
    this.getCommentForm = function() {
        var commentform_template = new Template(
            '<div class="commentpanel panel"><form id="add_comment" action="" onsubmit="return this.checkCommentForm()">'
            + '<div><label for="comment_content">Comment:</label></div>'
            + '<textarea id="comment_content" name="comment_content"></textarea><br />'
            + '<div class="buttonpanel"><input type="button" id="comment_submit" value="Send" /></div>'
            + '<input id="comment_nickname" type="hidden" name="comment_nickname" value="#{author}" />'
            + '<input id="comment_tags" type="hidden" name="comment_tags" value="#{mytags}"/>'
            + '</form></div>'
        );
        var comment_values = {}
        comment_values['mytags'] = connector.getMyTags(infohash, torrent, collection);
        comment_values['author'] = Util.getRealName();
        return commentform_template.evaluate(comment_values);
    }

    var status = HttpConnector.doGet("/island/"+collection+"/status?info_hash="+infohash).evalJSON(true);
    var info = null;
    info = HttpConnector.doGet("/collection/"+collection+"/island/"+infohash+
                      "/info/"+torrent+"/?output=json&timeout=30").evalJSON(true);
    var torrentinfo = null;
    var tags = new Array();
    var comments = new Array();
    for (var i=0; i<info.data.length; i++) {
        if (info.data[i][0] == "info") {
            torrentinfo = info.data[i][1].evalJSON(true);
        } else if (/^tags/.test(info.data[i][0])) {
            tags.push(info.data[i]);
        } else if (/^comments/.test(info.data[i][0])) {
            comments.push(info.data[i]);
        }
    }

    var html = '<div class="thisplace"><h1><a href="/collection/' + collection + '/web/index.html"><img src="/static/icons/fusion_island.png" alt="" />' + HttpConnector.doGet('/collection/'+collection+'/info/title') + '<img src="/static/icons/fusion_island.png" alt="" /></a></h1>'

        html += "<div class=\"torrent_info\"><h2><a href=\"/collection/"+collection+"/island/"+infohash+"/file/"+torrent+"\"><img src=\"/static/icons/torrent_download.png\" alt=\"Download torrent file for \" />"+TrackerUtils.friendlyName(torrent)+"<img src=\"/static/icons/torrent_download.png\" alt=\"\" /></a></h2>"+
        "<p class=\"size\">( "+TrackerUtils.bytesToMbytes(parseInt(torrentinfo["size"]))+" )</p>"+
        "<p class=\"availability\">There are <strong>" + status["files"][infohash]["complete"] +
        "</strong> full copies of the content currently available.<br />"+
        "The <strong>" +
        status["files"][infohash]["incomplete"] +
        "</strong> downloaders may share some parts they managed to get.<br /><em>" +
        HttpConnector.doGet('/collection/'+collection+'/info/title') +
        "</em> has seen <strong>"+status["files"][infohash]["downloaded"]+"</strong> downloader succeed.</p>";

        if(torrentinfo["description"] != '')
        {
            html += "<p class=\"description\">"+torrentinfo["description"]+"</p>";
        }
        else
        {
            html += "<p class=\"description notavailable\">No description available.</p>";
        }
        html += "<p class=\"publisher\">published by <a href=\"/profile/"+torrentinfo['publisher']['profile']+"\"><em>"+torrentinfo['publisher']['name']+"</em></a>"+", "+Util.getUTCFriendlyDate(torrentinfo["published"])+"</p>"+
        "<hr />" +
        "<h3>Tags</h3><div id=\"tagcloud_holder\">"+
        
        TrackerUtils.getTagCloud(connector.getTags(infohash, torrent, collection), MAX_TAGS_ATTIME) +

        '</div><div class="yourtags panel"><table>' +
        '<tr><td class="yourtaglabel"><label for="comment_tags">Your tags:</label></td><td><input id="comment_tags" type="text" name="comment_tags" value="' +
        connector.getMyTags(infohash, torrent, collection) +
        '" /></td>' +
        '<td class="yourtagbutton"><input type="button" id="tag_submit" value="Save" /></td></tr>' +
        '</table></div>' +
        '<hr />' +
        '<h3>Comments</h3>' +
        "<div id=\"comments\">"+this.getComments()+"</div>" +
        this.getCommentForm() +
        '</div></div>';

        html += islandFooter();

    $('view').innerHTML += html

    $('comment_submit').onclick = function() {
        self.onMessageEntered();
    };

    $('tag_submit').onclick = function() {
        self.onTagEntered();
    };

    this.onMessageEntered = function(){
        var nick = $('comment_nickname').value;
        var msg = $('comment_content').value;
        var tags = $('comment_tags').value;
        if (nick==''){
            alert("Nickname cannot be empty");
            return;
        }
        $('comment_content').value = '';
        connector.postComment(infohash, torrent, nick, tags, msg, collection);
        
        $('comments').innerHTML = this.getComments();
    }

    this.onTagEntered = function(){
        var tags = $('comment_tags').value;
        connector.postComment(infohash, torrent, '', tags, '', collection);
        $('tagcloud_holder').innerHTML = TrackerUtils.getTagCloud(connector.getTags(infohash, torrent, collection), MAX_TAGS_ATTIME);
    }
}
